<?php declare(strict_types=1);


namespace PinWuYun\domain\service\youZanServer;

use Exception;
use linkcache\Cache;
use PinWuYun\domain\service\config\config;
use Youzan\Open\Token;

/**
 * Created: by zhiJie
 * Date: 2021/6/29
 */
class TokenServer
{
    const CACHE_KEY =  'you_zan_access_token_key';
    /**
     * // 获取refresh_token
     * [
     *  'refresh_token' => 358234a7c14ca3194a987bbb1ab790e
     *  'authority_id' => 96039699
     *  'access_token' =>
     *  'expires' =>  过期时间
     *  'scope' => 开放的接口
     * ]63deb2cdf96cbc1f61c986f0191c1fc
     *
        refresh_token： 1、用于刷新 access_token 的刷新令牌（过期时间：28 天）
        access_token 有效期7天
        code：  有效期2分钟
     *
     *
     */

    /**
     * 获取有赞accessToken
     * @throws Exception
     */
    public static function getAccessToken() {
        $cache = Cache::getInstance();
        // 如果要缓存直接拿缓存
        if($cache->get(self::CACHE_KEY)) {
            return $cache->get(self::CACHE_KEY);
        }
        $systemConfig = (new config)->getConfigGroup(['client_id', 'client_secret', 'kdt_id']);
        // 发送网络请求去获取
        $config['refresh'] = true;
        $resp = (new Token($systemConfig['client_id'], $systemConfig['client_secret']))
            ->getSelfAppToken($systemConfig['kdt_id'], $config);
        $cache->set(self::CACHE_KEY, $resp['access_token'], 60*60*24*7);
        if(!$resp['success']) {
            throw new Exception('获取有赞access_token失败：'.$resp['message']);
        }
        return $resp['access_token'];
    }
}